package cn.edu.ujs.coor.common.aspect;

import cn.edu.ujs.coor.model.User;
import cn.edu.ujs.coor.request.PageRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataAspect {

    @Pointcut("@annotation(cn.edu.ujs.coor.common.annotation.DataLevel)")
    public void dataCut(){}

    @Before("dataCut()")
    public void before(JoinPoint joinPoint) {
        PageRequest request = null;
        User user = null;
        Object args[] = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof PageRequest) {
                request = (PageRequest) arg;
                continue;
            }
            if (arg instanceof User) {
                user = (User) arg;
                continue;
            }
        }
        // 设定数据权限级别
        if (request != null && user != null) {
            // 超级管理员过滤一切
            if ("admin".equals(user.getId())) {
                return;
            }
            if ("0".equals(user.getDataLevel())) {
                request.setUserId(user.getId());
                return;
            }
            if ("1".equals(user.getDataLevel())) {
                request.setOrganizationId(user.getOrganizationId());
                return;
            }
        }
    }
}
